package xin.xueqing.base.controller;


import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import springfox.documentation.annotations.ApiIgnore;
import xin.xueqing.base.common.BaseController;
import xin.xueqing.base.common.ex.CustomerException;
import xin.xueqing.base.common.utils.FileUtil;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.Optional;

import static xin.xueqing.base.config.Constant.UPLOAD_FILE_PATH;

/**
 * @create: 20191217
 * @author: xueqing wang
 **/
@RestController
@EnableAutoConfiguration
@RequestMapping("/adminApi/file")
@Api(value = "文件上传管理Controller", tags = "文件上传管理Controller")
public class FileController  {



    @ApiOperation(value = "文件上传")
    @PostMapping(value = "/fileUpload")
    public ResponseEntity fileUpload(MultipartFile file) throws IOException {

        if (!Optional.ofNullable(file.getOriginalFilename()).isPresent()) {
            throw new CustomerException("请选择文件");
        }

       File f =  FileUtil.upload(file, UPLOAD_FILE_PATH);

        return new ResponseEntity(f.getName(), HttpStatus.OK);


    }


    @ApiIgnore
    @ApiOperation("文件下载")
    @RequestMapping(value = "/downloadFile")
    public void download(HttpServletRequest request, HttpServletResponse response, String path) {
        FileUtil.downloadFile(request, response, new File(UPLOAD_FILE_PATH + "/" + path), false);
    }

}
